package Database;
import java.io.IOException;
import java.util.Random;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XMLProvider {
	public static DocumentBuilderFactory docFactory;
	public static DocumentBuilder docBuilder;
	public static Document docWanted;
	public static Document docPerson;
	public static final int RELEASE_KEY = 5;
	
	public static void LoadXML()
	{
		try
		{
			docFactory = DocumentBuilderFactory.newInstance();
			docBuilder = docFactory.newDocumentBuilder();
			docWanted = docBuilder.parse("Data/Wanted.xml");
			docPerson = docBuilder.parse("Data/Person.xml");
		}
		catch (Exception ex)
		{
			
		}
	}
	public static boolean SaveXML()
	{
		try
		{
			DOMSource source = new DOMSource(docWanted);
	
	        TransformerFactory transformerFactory = TransformerFactory.newInstance();
	        Transformer transformer = transformerFactory.newTransformer();
	        StreamResult result = new StreamResult("Data/Wanted.xml");
	        transformer.transform(source, result);
        	return true;
		}
		catch (Exception ex)
		{
			return false;
		}
	}
	public static Person GetPersonbyID(String id) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException
	{
		XPathFactory factory = javax.xml.xpath.XPathFactory.newInstance();
		XPath xPath = factory.newXPath();
		
		XPathExpression expression =  xPath.compile("//Persons//Person[@id='"+id +"']//FirstName");
		String firstname = expression.evaluate(docPerson,XPathConstants.STRING).toString();
		expression =  xPath.compile("//Persons//Person[@id='"+id +"']//LastName");
		String lastName = expression.evaluate(docPerson,XPathConstants.STRING).toString();
		
		expression =  xPath.compile("//Persons//Person[@id='"+id +"']//DoB");
		String DoB = expression.evaluate(docPerson,XPathConstants.STRING).toString();
		
		expression =  xPath.compile("//Persons//Person[@id='"+id +"']//PoB");
		String FoB = expression.evaluate(docPerson,XPathConstants.STRING).toString();
		
		expression =  xPath.compile("//Persons//Person[@id='"+id +"']//Nationality");
		String Nationality = expression.evaluate(docPerson,XPathConstants.STRING).toString();
		
		expression =  xPath.compile("//Persons//Person[@id='"+id +"']//Address");
		String Address = expression.evaluate(docPerson,XPathConstants.STRING).toString();
		
		Person ps = new Person(id, firstname, lastName, DoB, FoB, lastName, Address);
		return ps;
	}
	public static Wanted getWantedbyPersonID(String id) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException
	{
		XPathFactory factory = javax.xml.xpath.XPathFactory.newInstance();
		XPath xPath = factory.newXPath();
		
		XPathExpression expression =  xPath.compile("//Wanteds//Wanted[Person='"+id+"']//Person");
		String person = expression.evaluate(docWanted,XPathConstants.STRING).toString();
		if (person == "")
			return null;
		else{
			expression =  xPath.compile("//Wanteds//Wanted[Person='"+id+"']//RqAction");
			String Rq = expression.evaluate(docWanted,XPathConstants.STRING).toString();
			Integer RqAction = Integer.parseInt(Rq);
			
			expression =  xPath.compile("//Wanteds//Wanted[Person='"+id+"']//RqDepartment");
			String RqDepartment = expression.evaluate(docWanted,XPathConstants.STRING).toString();
			
			expression =  xPath.compile("//Wanteds//Wanted[Person='"+id+"']//RqNumber");
			String RqNumber = expression.evaluate(docWanted,XPathConstants.STRING).toString();
			
			expression =  xPath.compile("//Wanteds//Wanted[Person='"+id+"']//RqLetters");
			String RqLetters = expression.evaluate(docWanted,XPathConstants.STRING).toString();
			
			expression =  xPath.compile("//Wanteds//Wanted[Person='"+id+"']//RqDate");
			String RqDate = expression.evaluate(docWanted,XPathConstants.STRING).toString();
			 
			expression =  xPath.compile("//Wanteds//Wanted[Person='"+id+"']");
			Element nl = (Element)expression.evaluate(docWanted,XPathConstants.NODE);
			String wid =nl.getAttribute("id");
			
		
			Wanted wanted = new Wanted(wid,person, RqAction, RqDepartment, RqLetters, RqNumber, RqDate);
			return wanted;
		}
		
	}
	public static Wanted getWantedbyWantedID(String id) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException
	{
		XPathFactory factory = javax.xml.xpath.XPathFactory.newInstance();
		XPath xPath = factory.newXPath();
		
		XPathExpression expression =  xPath.compile("//Wanteds//Wanted[@id='"+id+"']//Person");
		String person = expression.evaluate(docWanted,XPathConstants.STRING).toString();
		if(person == "")
			return null;
		else{
			expression =  xPath.compile("//Wanteds//Wanted[@id='"+id+"']//RqAction");
			String Rq = expression.evaluate(docWanted,XPathConstants.STRING).toString();
			Integer RqAction = Integer.parseInt(Rq);
			
			expression =  xPath.compile("//Wanteds//Wanted[@id='"+id+"']//RqDepartment");
			String RqDepartment = expression.evaluate(docWanted,XPathConstants.STRING).toString();
			
			expression =  xPath.compile("//Wanteds//Wanted[@id='"+id+"']//RqNumber");
			String RqNumber = expression.evaluate(docWanted,XPathConstants.STRING).toString();
			
			expression =  xPath.compile("//Wanteds//Wanted[@id='"+id+"']//RqLetters");
			String RqLetters = expression.evaluate(docWanted,XPathConstants.STRING).toString();
			
			expression =  xPath.compile("//Wanteds//Wanted[@id='"+id+"']//RqDate");
			String RqDate = expression.evaluate(docWanted,XPathConstants.STRING).toString();
			
			Wanted wanted = new Wanted(id,person, RqAction, RqDepartment, RqLetters, RqNumber, RqDate);
			return wanted;
		}
	}

	public static String generateWantedID()
	{
		Random generator = new Random();
		int id = generator.nextInt(65536);
		return String.valueOf(id);
	}
	
	public static boolean addWanted(Wanted wanted)
	{
		try
		{			
			Element newWanted = docWanted.createElement("Wanted");
			newWanted.setAttribute("id", wanted.getID());
			
			Element newPerson = newElement("Person", wanted.getPersonID(), docWanted);
			Element newRqAction = newElement("RqAction", String.valueOf(wanted.getRequireAction()), docWanted);
			Element newRqDepartment = newElement("RqDepartment", wanted.getDepartmentName(), docWanted);
			Element newRqNumber = newElement("RqNumber", wanted.getDepartmentNumber(), docWanted);
			Element newRqLetters = newElement("RqLetters", wanted.getDepartmentLetter(), docWanted);
			Element newRqDate = newElement("RqDate", wanted.getRequestDate(), docWanted);			
			
			newWanted.appendChild(newPerson);
			newWanted.appendChild(newRqAction);
			newWanted.appendChild(newRqDepartment);
			newWanted.appendChild(newRqNumber);
			newWanted.appendChild(newRqLetters);
			newWanted.appendChild(newRqDate);
			
			Element root = docWanted.getDocumentElement();
			root.appendChild(newWanted);
			
			return SaveXML();
		}
		catch (Exception ex)
		{
			return false;
		}
	}
	
	private static Element newElement(String element, String value, Document doc)
	{
		Element newElement = doc.createElement(element);
		newElement.setTextContent(value);
		
		return newElement;
	}

	public static boolean updateWanted(Wanted wanted)
	{
		try
		{
			NodeList nodelst = (NodeList)docWanted.getElementsByTagName("Wanted");
			
			for (int i = 0; i < nodelst.getLength(); i++)
			{
				Node node = (Node)nodelst.item(i);
				NamedNodeMap attr = node.getAttributes();
				Node nodeAttr = attr.getNamedItem("id");
				if(nodeAttr.getNodeValue().equals(wanted.getID()))
				{
					NodeList list = node.getChildNodes();
					
					for (int a = 0; a < list.getLength(); a++) {
						Node inode = list.item(a);
						 
							String nodename =inode.getNodeName();
						   // get the salary element, and update the value
						   if ("Person".equals(nodename)) {
							inode.setTextContent(wanted.getPersonID());
						   }
							if ("RqAction".equals(nodename)) {
								inode.setTextContent(wanted.getRequireAction().toString());
							}
							if ("RqDepartment".equals(nodename)) {
								inode.setTextContent(wanted.getDepartmentName());
							}
							if ("RqNumber".equals(nodename)) {
								inode.setTextContent(wanted.getDepartmentNumber());
							}
							if ("RqLetters".equals(nodename)) {
								inode.setTextContent(wanted.getDepartmentLetter());
							}
							if ("RqDate".equals(nodename)) {
								inode.setTextContent(wanted.getRequestDate());
							}
						   }
					return SaveXML();
					}
					/*
					Node personID =  (Node) node.getElementsByTagName("Person");
					Node RqAction = (Node) node.getElementsByTagName("RqAction");
					Node RqDepartment = (Node) node.getElementsByTagName("RqDepartment");
					Node RqNumber = (Node) node.getElementsByTagName("RqNumber");
					Node RqLetters = (Node) node.getElementsByTagName("RqLetters");
					Node RqDate = (Node) node.getElementsByTagName("RqDate");
					
					personID.setTextContent(wanted.getPersonID());
					RqAction.setTextContent(String.valueOf(wanted.getRequireAction()));
					RqDepartment.setTextContent(wanted.getDepartmentName());
					RqNumber.setTextContent(wanted.getDepartmentNumber());
					RqLetters.setTextContent(wanted.getDepartmentLetter());
					RqDate.setTextContent(wanted.getRequestDate());
					*/
						
					
				}
			return false;
		}
		catch (Exception ex)
		{
			return false;
		}
	}

	public static boolean deleteWanted(Wanted wanted)
	{
		try
		{
			NodeList nodelst = (NodeList)docWanted.getElementsByTagName("Wanted");
			
			for (int i = 0; i < nodelst.getLength(); i++)
			{
				Node node = (Node)nodelst.item(i);
				NamedNodeMap attr = node.getAttributes();
				Node nodeAttr = attr.getNamedItem("id");
				if(nodeAttr.getNodeValue().equals(wanted.getID()))
				{
					NodeList list = node.getChildNodes();
					
					for (int a = 0; a < list.getLength(); a++) {
						Node inode = list.item(a);
							String nodename = inode.getNodeName();
						   

							if ("RqAction".equals(nodename)) {
								inode.setTextContent("5");
							}
						}
					return SaveXML();
				}
			
				}
			return false;
		}
		catch (Exception ex)
		{
			return false;
		}
	}
}
